package web;

import org.apache.commons.dbutils.DbUtils;
import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class RegistServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        Connection conn = JDBCUtils.getConnection();
        //1.获取请求的参数(html页面输入框内容)
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除session中的验证码，防止下次重复使用
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //2.检查验证码是否正确
        if (token.equalsIgnoreCase(code)) {
            //   正确：
            //     3.检查用户名是否可用(检查用户名是否存在于数据库中，不存在表示可用)
            //       不可用：
            if (userService.existsUsername(username)) {
                //把回显的信息保存在request域中
                req.setAttribute("msg","用户名已存在！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);

                System.out.println("用户名"+username+"已存在");
                //          跳回注册页面
                req.getRequestDispatcher("/pages/user/regist_bind(click_blur)事件.jsp").forward(req, resp);

            }
            //       可用：
            else {
                //          调用Service保存到数据库
                userService.registUser(new User(null, username, password, email));
                //          跳转到注册成功的页面 regist_success.jsp
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            //   不正确：
            //把回显的信息保存在request域中
            req.setAttribute("msg","验证码错误！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);

            System.out.println("验证码" + code + "错误");
            //   跳回注册页面
            req.getRequestDispatcher("/pages/user/regist_bind(click_blur)事件.jsp").forward(req, resp);
        }
        try {
            DbUtils.close(conn);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
